package net.kazed.nextaction.toplevel.activity;

import java.util.ArrayList;

import net.kazed.android.inject.InjectedActivity;
import net.kazed.nextaction.NextActionApplication;
import net.kazed.nextaction.R;
import net.kazed.nextaction.context.activity.DueTasksActivity;
import net.kazed.nextaction.context.activity.InboxActivity;
import net.kazed.nextaction.context.activity.StartedTasksActivity;
import net.kazed.nextaction.database.ContextCache;
import net.kazed.nextaction.database.GtdContext;
import net.kazed.nextaction.database.Task;
import net.kazed.nextaction.database.TreeNode;
import net.kazed.nextaction.menu.TimerOptionMenuItem;
import net.kazed.nextaction.timer.Notifier;
import net.kazed.nextaction.tools.BackupListActivity;
import net.kazed.nextaction.tools.PurgeActivity;
import net.kazed.nextaction.view.TextViewListBuilder;
import net.kazed.nextaction.view.TextViewListBuilder.TextViewBuilder;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Displays a list of the main activities.
 */
public class TopLevelActivity extends InjectedActivity {
    private static final String cTag = "TopLevelActivity";

    private static final int CONTEXTS = 0;
    private static final int STARTED_TASKS = CONTEXTS + 1;
    private static final int DUE_TASKS = STARTED_TASKS + 1;
    private static final int TOOLS = DUE_TASKS + 1;

    private static final int DIALOG_TIMER = 0;

	private static final int REQUEST_ADD_CONTEXT = 0;
	private static final int REQUEST_VIEW_CONTEXT = 1;
	private static final int REQUEST_EDIT_CONTEXT = 2;
    
    private TimerOptionMenuItem timerOptionMenuItem;

	private TextView inboxSubTitle;

	private ArrayList<GtdContext> contexts;
    
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
        setContentView(R.layout.home);
		View inboxRow = findViewById(R.id.inbox);
		inboxSubTitle = (TextView) inboxRow.findViewById(R.id.subtitle);
		inboxRow.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(final View v) {
		         startActivity(new Intent(TopLevelActivity.this, InboxActivity.class));
			}
		});
		View startedTasksRow = findViewById(R.id.started_tasks);
		startedTasksRow.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(final View v) {
				startActivity(new Intent(TopLevelActivity.this, StartedTasksActivity.class));
			}
		});
		View dueTasksRow = findViewById(R.id.due_tasks);
		dueTasksRow.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(final View v) {
				startActivity(new Intent(TopLevelActivity.this, DueTasksActivity.class));
			}
		});
    }
	
	@Override
	protected void onResume() {
        Log.d(cTag, "onResume+");
		super.onResume();

		// get counts for each item
		Cursor cursor;
		String[] projection = new String[] {"_id"};
		cursor = getContentResolver().query(Task.CONTENT_URI, projection, Task.INBOX_SELECTION, null, null);
		int inboxCount = cursor.getCount();
		cursor.close();
		
		Resources resources = getResources();
		inboxSubTitle.setText(resources.getQuantityString(R.plurals.inbox_number_of_tasks, inboxCount, inboxCount));
		
		LinearLayout listContainer = (LinearLayout) findViewById(R.id.context_container);
		listContainer.removeAllViews();
		TextViewListBuilder listBuilder = new TextViewListBuilder(this);
		listBuilder.listContainer(listContainer).textViewResource(R.layout.home_context_row).separatorLayout(R.layout.horizontal_text_separator);
        NextActionApplication application = (NextActionApplication) getApplication();
        ContextCache contextCache = application.getContextCache();
        TreeNode<GtdContext> rootNode = contextCache.getContextTree();
        contexts = new ArrayList<GtdContext>();
        for (TreeNode<GtdContext> node : rootNode.getChildren()) {
            final GtdContext gtdContext = node.getData();
            contexts.add(gtdContext);
            int numberOfTasks = gtdContext.getNumberOfTasks();
            String subTitle = resources.getQuantityString(R.plurals.context_number_of_tasks, numberOfTasks,
            		numberOfTasks);
            TextViewBuilder itemBuilder = listBuilder.createTextView();
	        itemBuilder.background(R.drawable.list_item_state).text(R.id.title, gtdContext.getName()).text(R.id.subtitle, subTitle);
	        itemBuilder.image(R.id.icon).invisible();
	        itemBuilder.onClickListener(new View.OnClickListener() {
	              @Override public void onClick(final View view) {
	            	  gotoContext(gtdContext);
	              }
	        });
	        itemBuilder.image(R.id.button, R.drawable.edit_icon).background(R.drawable.button_state)
        	.onClickListener(new View.OnClickListener() {
			@Override public void onClick(final View view) {
          	  editContext(gtdContext);
			}
		});
        }
        
        if (contexts.size() == 0) {
        	TextViewBuilder itemBuilder = listBuilder.createTextView();
        	itemBuilder.background(R.drawable.list_item_state)
        	.text(R.id.title, R.string.menu_add_context)
        	.text(R.id.subtitle, "")
        	.onClickListener(new View.OnClickListener() {
        		@Override public void onClick(final View view) {
        		}
        	});
        	itemBuilder.image(R.id.icon).invisible();
        	itemBuilder.image(R.id.button, R.drawable.plus).background(R.drawable.button_state)
        	.onClickListener(new View.OnClickListener() {
        		@Override public void onClick(final View view) {
        			addContext();
        		}
        	});
        }
	}

	private void editContext(final GtdContext gtdContext) {
        Uri itemUri = ContentUris.withAppendedId(GtdContext.CONTENT_URI, gtdContext.getId());
        Intent editIntent = new Intent(Intent.ACTION_EDIT, itemUri);
        startActivityForResult(editIntent, REQUEST_EDIT_CONTEXT);
	}

	private void gotoContext(final GtdContext gtdContext) {
        Uri itemUri = ContentUris.withAppendedId(GtdContext.CONTENT_URI, gtdContext.getId());
        startActivityForResult(new Intent(Intent.ACTION_VIEW, itemUri), REQUEST_VIEW_CONTEXT);
	}

	private void addContext() {
	   GtdContext newContext = new GtdContext("New context");
	   ContentValues values = new ContentValues();
	   newContext.toValues(values);
	   Uri newContextUri = getContentResolver().insert(GtdContext.CONTENT_URI, values);
	   Intent contextIntent = new Intent(Intent.ACTION_INSERT, newContextUri);
	   startActivityForResult(contextIntent, REQUEST_ADD_CONTEXT);
   }

   @Override
   public boolean onCreateOptionsMenu(final Menu menu) {
       MenuInflater inflater = getMenuInflater();
       inflater.inflate(R.menu.home, menu);
       timerOptionMenuItem = new TimerOptionMenuItem(getApplicationContext(), this, R.id.menu_timer);
       return super.onCreateOptionsMenu(menu);
   }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       boolean handled = false;
       switch (item.getItemId()) {
       case R.id.menu_timer:
          showDialog(DIALOG_TIMER);
          handled = true;
          break;
       case R.id.menu_insert_context:
    	   addContext();
           handled = true;
          break;
       case R.id.menu_tool_backup:
    	   startActivity(new Intent(this, BackupListActivity.class));
           handled = true;
          break;
       case R.id.menu_tool_purge:
    	   startActivity(new Intent(this, PurgeActivity.class));
           handled = true;
          break;
       case R.id.menu_help:
    	   startActivity(new Intent(this, HelpActivity.class));
           handled = true;
          break;
       }

        if (!handled) {
           handled = super.onOptionsItemSelected(item);
        }
        return handled;
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
       Dialog dialog = null;
       switch (id) {
       case DIALOG_TIMER:
          dialog = timerOptionMenuItem.createDialog(this, Notifier.TOPLEVEL_CONTENT_TIMER_URI);
          break;
       default:
          dialog = super.onCreateDialog(id);
          break;
       }
       return dialog;
    }

}
